/* eslint-disable no-unused-vars */
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'

const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}

const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  CLEARUSERINFO(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}

const actions = {
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      commit("GETCODE", result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userLogin({ commit }, user) {
    let result = await reqUserLogin(user)
    if (result.code == 200) {
      commit("USERLOGIN", result.data.token)
      setToken(result.data.token);
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo();
    if (result.code == 200) {
      commit("GETUSERINFO", result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userLogout({ commit }) {
    let result = await reqLogout();
    // action中不能操作state，需要提交到mutation
    if (result.code == 200) {
      commit("CLEARUSERINFO");
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }
}

const getters = {

}

export default ({
  state,
  mutations,
  actions,
  getters
})